#include "EditFormationMenu.h"
#include "Utilities.h"
#include "PrintUtilities.h"
#include "MarketMenu.h"
#include "UserManager.h"
#include "ServiceProvider.h"
#include "MenuManager.h"
#include "Team.h"
#include "GamePrintUtils.h"

EditFormationMenu::EditFormationMenu(MenuManager* const i_menuManager)
	: Menu(i_menuManager)
{
}

void EditFormationMenu::OnEnter()
{
	m_editing = false;
	m_firstPlayerSelected = false;
	m_input = 0;
}

void EditFormationMenu::Draw() const
{
	const UsersList& users = GetSP()->GetUserMgr().GetUserList();
	const Team& team = *(users[m_userIndex]->m_team);

	std::cout << Print::Title("\"" + team.GetName() + "\" FORMATION MANAGEMENT:");
	PrintTeam(std::cout, team);

	if (!m_editing)
		std::cout	<< Print::Options(
						"1) Edit formation.\n"
						"2) Goto market.\n\n"
						"0) Return to previous menu'.")
					<< " Selection: ";
	else 
	{	
		if (!m_firstPlayerSelected) 
			std::cout	<< "Choose titolar to remove: ";
		else
			std::cout	<< "Choose panchinar to make titolar: ";
	}
}


bool EditFormationMenu::Input(const std::string& i_input)
{
	bool goodInput = true;
	const int TitolarPlayers = Team::GetParams().TITOLARS_PLAYERS;

	int res = Utilities::StringToInt(i_input);

	if (m_editing)
	{
		if (!m_firstPlayerSelected)
		{
			if (res > 0 && res <= TitolarPlayers)
			{
				m_input = res;
				m_firstPlayerSelected = true;
			}
			else 
				goodInput = false;
		}
		else
		{
			const UsersList& users = GetSP()->GetUserMgr().GetUserList();
			Team* team = users[m_userIndex]->m_team;
			if (res > TitolarPlayers && res <= static_cast<int>(team->GetNumPlayers()))
			{
				team->SwapPlayers(m_input - 1, res - 1);
				m_editing = false;
				m_firstPlayerSelected = false;
				m_input = 0;
			}
			else 
				goodInput = false;
		}
	}
	else
	{
		if (res == 0)
		{
			GetMM()->SetMenu(GetMM()->GetTeamsManagementMenu());
		}
		else if (res == 1)
			m_editing = true;
		else if (res == 2)
		{
			MarketMenu* market = static_cast<MarketMenu*>(GetMM()->GetMarketMenu());
			market->m_status = BROWSING;

			GetMM()->SetMenu(GetMM()->GetMarketMenu());
		}
	}
	return goodInput;
}